package article

import (
	"api/api/v1/admin"
	"api/internal/dao"
	"api/internal/library/liberr"
	"api/internal/model/entity"
	"api/internal/service"
	"context"

	"github.com/gogf/gf/v2/util/gconv"

	"github.com/gogf/gf/v2/frame/g"
)

type sArticle struct {
}

func init() {
	service.RegisterArticle(New())
}

func New() *sArticle {
	return &sArticle{}
}

func (s *sArticle) List(ctx context.Context, in *admin.ArticleListReq) (res *admin.ArticleListRes, err error) {
	res = new(admin.ArticleListRes)
	err = g.Try(ctx, func(ctx context.Context) {
		// 初始化条件与页码信息
		in.ConditionOrPaginate()
		m := dao.Article.Ctx(ctx)
		if in.Title != "" {
			m = m.WhereLike(dao.Article.Columns().Title, in.Title)
		}
		if in.Status != "" {
			m = m.Where(dao.Article.Columns().Status, gconv.Uint(in.Status))
		}
		res.Total, err = m.Count()
		liberr.IsNil(ctx, err, "获取文章数据失败")
		res.CurrentPage = in.PageNum
		err = m.Page(in.PageNum, in.PageSize).Order(in.OrderBy).Scan(&res.List)
		liberr.IsNil(ctx, err, "获取文章数据失败")
	})
	return
}

func (s *sArticle) Create(ctx context.Context, in *admin.ArticleCreateReq) (err error) {
	err = g.Try(ctx, func(ctx context.Context) {
		_, err = dao.Article.Ctx(ctx).Data(in).OmitEmpty().Save()
		liberr.IsNil(ctx, err, "添加文章失败")
	})
	return
}

func (s *sArticle) Update(ctx context.Context, in *admin.ArticleUpdateReq) (err error) {
	err = g.Try(ctx, func(ctx context.Context) {
		_, err = dao.Article.Ctx(ctx).Data(in).OmitEmpty().Where(dao.Article.Columns().Id, in.Id).Update()
		liberr.IsNil(ctx, err, "更新文章失败")
	})
	return
}

func (s *sArticle) Delete(ctx context.Context, in *admin.ArticleDeleteReq) (err error) {
	err = g.Try(ctx, func(ctx context.Context) {
		_, err = dao.Article.Ctx(ctx).WhereIn(dao.Article.Columns().Id, in.Ids).Delete()
		liberr.IsNil(ctx, err, "删除岗位失败")
	})
	return
}

// GetUsedPost 获取正常的岗位
func (s *sArticle) GetUsedPost(ctx context.Context) (list []*entity.Article, err error) {
	err = g.Try(ctx, func(ctx context.Context) {
		err = dao.Post.Ctx(ctx).Where(dao.Post.Columns().Status, 1).Order(dao.Post.Columns().PostSort+" asc", dao.Post.Columns().PostId+" id").Scan(&list)
	})
	return
}
